<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户" prop="customerId">
            <el-input v-model="formData.customerName" placeholder="请输入客户" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="拥有人" prop="ownerId">
            <el-select v-model="formData.ownerId" placeholder="请输入拥有人">
              <el-option
                v-for="dict in ownerList"
                :key="dict.id"
                :label="dict.nickname"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="跟进方式" prop="followType">
            <el-select
              v-model="formData.followType"
              placeholder="请输入跟进方式"
              :empty-values="[0]"
              :value-on-clear="0"
              clearable
              filterable
            >
              <el-option
                v-for="item in customerFollowModuleField.immutableFields.get('followType')?.options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="跟进时间" prop="followTime">
            <el-date-picker
              v-model="formData.followTime"
              placeholder="请输入跟进时间"
              :clearable="true"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="mb-2">
        <el-upload
          :multiple="true"
          v-model:file-list="imageList"
          :http-request="imageUploadRequest"
          :before-upload="beforeUpload"
          :show-file-list="false"
        >
          <el-button><Icon icon="material-symbols:imagesmode-outline" />图片</el-button>
        </el-upload>

        <el-upload
          :multiple="true"
          v-model:file-list="attachmentList"
          :http-request="fileUploadRequest"
          :before-upload="beforeUpload"
          :show-file-list="false"
          class="ml-2.5"
        >
          <el-button>
            <Icon icon="ic:baseline-attach-file" style="transform: rotate(45deg)" />附件
          </el-button>
        </el-upload>

        <el-popover :visible="quickInputVisible" :width="230">
          <el-button
            v-for="(item, index) in quickInput"
            class="ml-3"
            style="border: none"
            :key="index"
            @click="handleQuickInputClick(index)"
          >
            {{ item }}
          </el-button>

          <template #reference>
            <el-button class="ml-2.5" @click="quickInputVisible = !quickInputVisible">
              <Icon icon="material-symbols:chat-outline" />常用输入
            </el-button>
          </template>
        </el-popover>
      </el-row>
      <el-row v-if="imageList.length > 0">
        <el-col :span="24">
          <UploadImgs height="50px" width="50px" v-model="imageList" />
        </el-col>
      </el-row>

      <div style="display: flex; flex-wrap: wrap; margin: 5px 0">
        <div
          v-for="resourceItem in attachmentList"
          :key="resourceItem.name"
          @click="handleResourceClick(resourceItem)"
          @contextmenu="(event) => handleResourceRightClick(event, resourceItem)"
          class="file-list"
          :class="{ 'resource-selected': selectedItem?.name === resourceItem.name }"
        >
          <icon
            :size="30"
            style="margin: 5px"
            :icon="MailUtil.convertFileIcon(resourceItem.name)"
          />
          <div>
            <span>{{ MailUtil.truncateFileName(resourceItem.name) }}</span>
            <span>{{ MailUtil.formatBytes(resourceItem.size) }}</span>
          </div>
        </div>
        <ContextMenu v-model:show="fileMenuOption.show" :options="fileMenuOption.option">
          <div>
            <context-menu-item label="删除" @click="handleDeleteResource()" />
          </div>
        </ContextMenu>
      </div>

      <el-row>
        <el-col :span="24">
          <el-form-item label="内容" prop="content">
            <el-input
              v-model="formData.content"
              placeholder="请输入内容"
              :clearable="true"
              type="textarea"
              :autosize="{ minRows: 10 }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="定位图片">
          <UploadImgs height="70px" width="80px" v-model="positionImageList" />
        </el-form-item>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup name="CustomerCreateFollow" lang="ts">
import type { FormRules, UploadProps, UploadUserFile, UploadRawFile } from 'element-plus'

import * as UserApi from '@/api/system/user/user'
import * as FileApi from '@/api/infra/file'
import * as CustomerApi from '@/api/customer/customer'
import { SettingBusinessModuleEnum } from '@/utils/constants'
import * as MailUtil from '@/views/mailbox/mail/MailUtil'
import { CustomerFollowResourceTypeEnum } from '@/utils/constants'
import { getBussinessModule } from '@/views/setting/businessField/BusinessFieldUtil'
const quickInputVisible = ref(false)

const fileMenuOption = ref({
  show: false,
  option: { zIndex: 3000, minWidth: 130, x: 500, y: 200, theme: 'default' }
})
const selectedItem = ref<any>(null)

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const imageList = ref<UploadUserFile[]>([])
const attachmentList = ref<UploadUserFile[]>([])
const positionImageList = ref<UploadUserFile[]>([])
const ownerList = ref()
const dialogTitle = ref('新增跟进')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const customerFollowModuleField = ref()
const formData = ref({
  customerId: undefined,
  customerName: '',
  ownerId: undefined,
  followType: 0,
  followTime: undefined,
  content: '',
  deptId: 0,
  resources: [] as any[]
})
interface RuleForm {
  ownerId: number
  followTime: string
  followType: number
  content: string
}
const formRules = ref<FormRules<RuleForm>>({
  ownerId: [{ required: true, message: '请选择所属人', trigger: 'change' }],
  followTime: [{ required: true, message: '请选择跟进时间', trigger: 'change' }],
  content: [{ required: true, message: '请输入内容', trigger: 'change' }]
})

const quickInput = [
  '客户询价，已推荐方案',
  '邀请客户验厂',
  '已报价，客户压价',
  '和客户沟通交期',
  '客户确认到款时间',
  '客户已付款',
  '暂无需求',
  '暂时很忙没时间',
  '询盘价值低，不值得跟进',
  '给客户发产品资料',
  '给客户寄样品',
  '长期跟进'
]
/** 打开弹窗 */
const open = async (customerInfo) => {
  await dataInit(customerInfo)
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const dataInit = async (customerInfo) => {
  quickInputVisible.value = false
  formData.value = {
    customerId: undefined,
    customerName: '',
    ownerId: undefined,
    followType: 0,
    followTime: undefined,
    content: '',
    deptId: 0,
    resources: []
  }
  imageList.value = []
  attachmentList.value = []
  positionImageList.value = []
  formData.value.customerName = customerInfo.name
  formData.value.customerId = customerInfo.id
  formData.value.deptId = customerInfo.deptId
  ownerList.value = await UserApi.getOwnerUser()
  formData.value.ownerId = customerInfo.ownerId

  // 加载业务字段
  customerFollowModuleField.value = await getBussinessModule(
    SettingBusinessModuleEnum.CUSTOMER_FOLLOW
  )
}

// 文件上传之前判断
const beforeUpload: UploadProps['beforeUpload'] = (file: UploadRawFile) => {
  const isLimit = file.size < 32 * 1024 * 1024
  if (!isLimit) {
    message.error(`上传文件大小不能超过32MB!`)
    return false
  }
}

const imageUploadRequest = async (options) => {
  const res = await FileApi.uploadFile({
    file: options.file
  })

  imageList.value.forEach((file) => {
    if (file.name == options.file.name) {
      file.url = res.data
    }
  })
}

const fileUploadRequest = async (options) => {
  const res = await FileApi.uploadFile({
    file: options.file
  })

  attachmentList.value.forEach((file) => {
    if (file.name == options.file.name) {
      file.url = res.data
    }
  })
}

const handleResourceClick = (fileItem) => {
  selectedItem.value = fileItem
}

const handleResourceRightClick = (event, fileItem) => {
  event.preventDefault()
  const { x, y } = event
  fileMenuOption.value.show = true
  fileMenuOption.value.option.x = x
  fileMenuOption.value.option.y = y
  selectedItem.value = fileItem
}

const handleDeleteResource = () => {
  attachmentList.value = attachmentList.value.filter((resourceItem) => {
    if (resourceItem.name == selectedItem.value.name) return false
    else return true
  })
}

const handleQuickInputClick = (index) => {
  formData.value.content = quickInput[index]
  quickInputVisible.value = false
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验
  if (!formRef) return
  await formRef.value.validate()

  imageList.value.forEach((image) => {
    formData.value.resources.push({
      resourceType: CustomerFollowResourceTypeEnum.IMAGE,
      size: image.size,
      fileName: image.name,
      urlName: image.url
    })
  })
  attachmentList.value.forEach((image) => {
    formData.value.resources.push({
      resourceType: CustomerFollowResourceTypeEnum.ATTACHMENT,
      size: image.size,
      fileName: image.name,
      urlName: image.url
    })
  })
  positionImageList.value.forEach((image) => {
    formData.value.resources.push({
      resourceType: CustomerFollowResourceTypeEnum.POSITION_IMAGE,
      size: image.size,
      fileName: image.name,
      urlName: image.url
    })
  })
  await CustomerApi.createFollow(formData.value)
  message.success(t('common.createSuccess'))
  dialogVisible.value = false
  emit('success')
}
</script>
<style scoped>
.file-list {
  border: 0.5px solid #eaeaea;
  width: 200px;
  min-width: 200px;
  display: flex;
  flex-wrap: wrap;
  margin-right: 8px;
  margin-bottom: 5px;
}
.file-list > div {
  overflow: hidden;
  display: flex;
  flex-direction: column; /* 垂直排列 */
  align-items: left; /* 水平居中对齐 */
  justify-content: center; /* 垂直居中对齐 */
}

.file-list span {
  cursor: default;
  font-size: 10pt;
}

.resource-selected {
  background-color: #d9ebff;
  border: 1px solid #9cb4d0;
}
</style>
